<?php
namespace app\api\model;

use think\Model;
use think\exception\ValidateException;

class Shop extends Model
{
    // 数据库表名，不含前缀
    protected $name = 'shop';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 店铺状态
    const SS_STATUS_NO = 0;
    const SS_STATUS_WAIT = 1;
    const SS_STATUS_RETURN= 2;
    const SS_STATUS_SUCCESS = 3;


    public static function getStatusStr()
    {
        return [
            self::SS_STATUS_NO => '禁用',
            self::SS_STATUS_WAIT => '待审核',
            self::SS_STATUS_RETURN => '驳回',
            self::SS_STATUS_SUCCESS => '审核通过',
        ];
    }

    /*
    * 根据app_type获取对应(店铺类型)配置
    * value传递是可更具枚举值查对应中文
    */
    public function getShopType($app_type,$value='')
    {
        $shopsType=config('shoptype.platforms.'.$app_type)??[];
        if($value){
            return  $shopsType[$value]??'';
        }else{
            return  $shopsType;
        }
    }


    /**
     * 店铺新增
     */
    public function shopCreate($param)
    {
        // 验证数据
        try {
            validate([
                'appid'  => 'require', 
                'store_id'  => 'require', 
                'app_type'  => 'require', 
                'store_name'  => 'require', 
                'phone'  => 'require', 
                'latitude'  => 'require', 
                'longitude'  => 'require', 
            ])->message([
                'appid.require'  => 'appid必须传递',   
                'store_id.require'  => 'store_id必须传递',   
                'app_type.require'  => 'app_type必须传递',   
                'store_name.require'  => 'store_name必须传递',   
                'phone.require'  => 'phone必须传递',   
                'latitude.require'  => 'latitude必须传递',   
                'longitude.require'  => 'longitude必须传递',   
            ])->check($param);
        } catch (ValidateException $e) {
            return result_error($e->getError());
        }

        // 获取请求参数
        $data = [
            'appid' => $param['appid']??'',//appid
            'app_type' => $param['app_type']??'',//第三方平台类型 1:闪送, 2:达达,3:蜂鸟
            'store_id' => $param['store_id']??'',//第三方配送平台店铺唯一标识
            'platform_store_id' => $param['platform_store_id']??'',//调用方店铺唯一标识(同一个店铺传同一个id)
            'pro_dev' => $param['pro_dev']??'',//1测试2正式
            'store_name' => $param['store_name']??'',//店铺名称
            'city_name' => $param['city_name']??'',//城市名称
            'address' => $param['address']??'',//地址
            'address_detail' => $param['address_detail']??'',//详细地址
            'latitude' => floatval($param['latitude'])??'',//纬度（百度坐标系）
            'longitude' => floatval($param['longitude'])??'',//经度（百度坐标系）
            'phone' => $param['phone']??'',//手机号
            'good_type' => $param['good_type']??'',//业务类型
            'contact_name' => $param['contact_name']??'',//联系人姓名
            'settlement_type' => $param['settlement_type']??'',//结算方式 0:非独立结算, 1:独立结算
            'status' => $param['status']??'',//商户状态
        ];

        // 创建店铺
        try {
            $result = $this->save($data);
            if ($result) {
                return result_success('success',$result);
            } else {
                return result_error('保存失败');
            }
        } catch (\Exception $e) {
            return result_error($e->getMessage());
        }
    }

    /**
     * 店铺更新
     */
    public function shopUpdate($param)
    {
        // 验证数据
        if (empty($param['store_id']) &&  empty($param['id'])) {
            return result_error('缺少必要更新条件');
        }

        if(isset($param['store_name'])) $data['store_name'] = $param['store_name'];//店铺名称
        if(isset($param['city_name'])) $data['city_name'] = $param['city_name'];//城市名称
        if(isset($param['address'])) $data['address'] = $param['address'];//地址
        if(isset($param['address_detail'])) $data['address_detail'] = $param['address_detail'];//详细地址
        if(isset($param['latitude'])) $data['latitude'] = $param['latitude'];//纬度（百度坐标系）
        if(isset($param['longitude'])) $data['longitude'] = $param['longitude'];//经度（百度坐标系）
        if(isset($param['phone'])) $data['phone'] = $param['phone'];//手机号
        if(isset($param['good_type'])) $data['good_type'] = $param['good_type'];//业务类型
        if(isset($param['contact_name'])) $data['contact_name'] = $param['contact_name'];//联系人姓名
        if(isset($param['settlement_type'])) $data['settlement_type'] = $param['settlement_type'];//结算方式 0:非独立结算, 1:独立结算
        if(isset($param['status'])) $data['status'] = $param['status'];//商户状态


        // 更新店铺
        try {
          
            $find = $this
                    ->when(isset($param['store_id']),function ($query) use($param) {
                        $query->where('store_id', $param['store_id']);
                    })
                    ->when(isset($param['id']),function ($query) use($param) {
                        $query->where('id', $param['id']);
                    })
                    ->find();
            if (!$find){
                return  result_error('未查询到店铺');
            }  
            
            $result=$find->save($data);

           if ($result) {
                return result_success('success',$result);
            } else {
                return result_error('保存失败');
            }
        } catch (\Exception $e) {
            return result_error($e->getMessage());
        }
    }


    /**
     * 批量新增店铺
     */
    public function shopListSave($params)
    {
        // 获取请求参数
        $datas = [];
        foreach ($params as $key => $param){
            $datas[] = [
                'appid' => $param['appid']??"",
                'app_type' => $param['app_type']??"",
                'store_id' => $param['store_id']??"",
                'platform_store_id' => $param['platform_store_id']??"",
                'store_name' => $param['store_name']??"",
                'city_name' => $param['city_name']??"",
                'address' => $param['address']??"",
                'address_detail' => $param['address_detail']??"",
                'latitude' => floatval($param['latitude'])??"",
                'longitude' => floatval($param['longitude'])??"",
                'contact_name' => $param['contact_name'] ?? "",
                'phone' => $param['phone']??"",
                'good_type' => $param['good_type']??"",
            ];
        }
        // 批量新增店铺
        try {
            $result = $this->saveAll($datas)->toArray();
            if ($result) {
                return result_success('success',$result);
            } else {
                return result_error('保存失败');
            }
        } catch (\Exception $e) {
            return result_error($e->getMessage());
        }
    }


}
